<template>
    <div class="app-container">
      <div class="filter-container">
        <el-input v-model="listQuery.name" placeholder="Name" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />&nbsp;
        <el-select v-model="listQuery.college" placeholder="College" clearable style="width: 150px" class="filter-item">
          <el-option v-for="item in collegeListOptions" :key="item" :label="item" :value="item" />
        </el-select>&nbsp;
        <el-select v-model="listQuery.major" placeholder="Major" clearable style="width: 150px" class="filter-item">
          <el-option v-for="item in majorListOptions" :key="item" :label="item" :value="item" />
        </el-select>&nbsp;
        <el-select v-model="listQuery.status" placeholder="Status" clearable class="filter-item" style="width: 150px">
          <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
        </el-select>&nbsp;
        <el-select v-model="listQuery.sort" style="width: 150px" class="filter-item" @change="handleFilter">
          <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>&nbsp;
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          Search
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          Add
        </el-button>
        <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          Export
        </el-button>
      </div>
  
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="auto" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
  
        <!-- 学号 -->
        <el-table-column label="Sno" width="auto" align="center">
          <template slot-scope="{row}">
            <span>{{ row.sid }}</span>
          </template>
        </el-table-column>
  
        <!-- 姓名 -->
        <el-table-column label="Name" min-width="auto">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
          </template>
        </el-table-column>

        <!-- 省份 -->
        <el-table-column label="Province" width="auto" align="center">
          <template slot-scope="{row}">
            <span>{{ row.province }}</span>
          </template>
        </el-table-column>
  
        <!-- 学校 -->
        <el-table-column label="College" width="auto" align="center">
          <template slot-scope="{row}">
            <span>{{ row.college }}</span>
          </template>
        </el-table-column>
    
        <!-- 专业 -->
        <el-table-column label="Major" width="auto">
          <template slot-scope="{row}">
            <span>{{ row.major }}</span>
          </template>
        </el-table-column>
  
        <!-- 年级 -->
        <el-table-column label="Grade" width="auto">
          <template slot-scope="{row}">
            <span>{{ row.grade }}</span>
          </template>
        </el-table-column>

        <!-- 积分 -->
        <el-table-column label="Point" width="auto">
          <template slot-scope="{row}">
            <span>{{ row.point }}</span>
          </template>
        </el-table-column>

        <!-- 头像 -->
        <el-table-column label="Avatar" align="center" width="auto">
          <template slot-scope="{row}">
            <span >{{ row.avatar }}</span>
          </template>
        </el-table-column>

        <!-- 操作者 -->
        <el-table-column label="Operator" align="center" width="auto">
          <template slot-scope="{row}">
            <span>{{ row.operator }}</span>
          </template>
        </el-table-column>

        <!-- 操作日期 -->
        <el-table-column label="Date" width="auto" align="center">
          <template slot-scope="{row}">
            <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="Status" class-name="status-col" width="auto">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
  
        <!-- 操作 -->
        <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              修改
            </el-button>
            <el-button v-if="row.status!='active'" size="mini" type="sucess" @click="handleModifyStatus(row,'active')">
              激活
            </el-button>
            <el-button v-if="row.status!='inactive'" size="mini">
              已激活
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getStudentList" />
  
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="姓名" prop="name">
              <el-input v-model="temp.name" class="filter-item" placeholder=""></el-input>
          </el-form-item>
          
          <el-form-item label="学号" prop="sid">
            <el-input v-model="temp.sid" class="filter-item" placeholder=""></el-input>
          </el-form-item>

          <el-form-item label="学校" prop="college">
            <el-select v-model="temp.college"  class="filter-item" placeholder="请选择">
              <el-option v-for="item in collegeListOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="专业" prop="major">
            <el-select v-model="temp.major"class="filter-item" placeholder="请选择">
              <el-option v-for="item in majorListOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
    
          <el-form-item label="年级" prop="grade">
            <el-select v-model="temp.grade" class="filter-item" placeholder="请选择">
              <el-option v-for="item in gradeOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="省份" prop="province">
            <el-select v-model="temp.province" class="filter-item" placeholder="请选择">
              <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
  
          <el-form-item label="头像" prop="avatar">
            <Upload v-model="temp.avatar"></Upload>
          </el-form-item> 
        </el-form>
  
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createStudentData():updateStudentData()">
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  
  import {fetchStudentList, createStudent, updateStudent } from '@/api/student'
  import waves from '@/directive/waves'
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination'
  import Upload from '@/components/Upload/SingleImage'
  
  export default {
    name: 'ComplexTable',
    components: { Pagination, Upload },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          active: 'success',
          inactive: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined, //姓名
          sid: undefined, //学号
          province: undefined, //籍贯
          gender: undefined, //性别
          college:'', //学校
          major: '', //专业
          grade: undefined, //年级
          id_card:undefined, //身份证号码
          admission_number:undefined, //录取通知书编号
          point: undefined, //获得的积分
          avatar:undefined,
          sort: '+id'
        },
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['active', 'inactive','deleted'],//激活状态
        collegeListOptions:  ['大学A','大学B','大学C','大学D','大学E','大学F','大学G','大学H',
                      '大学I','大学J','大学K','大学L','大学M','大学N','大学O','大学P','大学Q',
                      '大学R','大学S','大学T','大学U','大学V','大学W','大学X','大学Y','大学Z'],
        majorListOptions: ['专业a','专业b','专业c','专业d','专业e','专业f','专业g','专业h',
                    '专业i','专业j','专业k','专业l','专业m','专业n','专业o','专业p','专业q',
                    '专业r','专业s','专业t','专业u','专业v','专业w','专业X','专业y','专业z'],
        gradeOptions: [18,19,20,21,22,23,24],
        provinceOptions: ['北京','天津','上海','重庆','香港','澳门','台湾','河北','山西','辽宁','吉林','黑龙江',
                      '江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','海南','四川','贵州',
                      '云南','陕西','甘肃','青海','内蒙古','广西','西藏','宁夏','新疆'],
        temp: {
          id: undefined,
          name: '',
          sid:'',
          college:'',
          major:'',
          grade:'',
          id_card:'',
          admission_number:'',
          point: '',
          status: 'inactive',//默认状态：未激活
          avatar:'',
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        rules: {
          point: [{ required: true, message: 'point is required', trigger: 'blur' }],
          name: [{ required: true, message: 'name is required', trigger: 'blur' }],
          sid: [{ required: true, message: 'sid is required', trigger: 'blur' }],
          college: [{ required: true, message: 'college is required', trigger: 'blur' }],
          id_card: [{ required: true, message: 'id_card is required', trigger: 'blur' }],
          admission_number: [{ required: true, message: 'admission_number is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    created() {
      this.getStudentList()
    },
    methods: {
      getStudentList() {
        this.listLoading = true
        fetchStudentList(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total
  
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      
      handleFilter() {
        this.listQuery.page = 1
        this.getStudentList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          remark: '',
          timestamp: new Date(),
          name: '',
          status: 'inactive',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createStudentData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'XinMiao_MS'
            createStudent(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateStudentData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp)
            updateStudent(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['id','name', 'type', 'point', 'status','operator','operateTime', 'status']
          const filterVal = ['id', 'name', 'type', 'point', 'status','operator','timestamp', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
  </script>